//
//  LTContactManager.m
//  LTIM
//
//  Created by 俊松何 on 2017/4/14.
//  Copyright © 2017年 俊松何. All rights reserved.
//

#import "LTContactManager.h"
#import "LTDBHelper.h"
#import "LTHTTPTool.h"
#import "LTClient.h"
#import "LTSendMessageHelper.h"
#import "LTUserConfig.h"
#import "LTFriendRecmondModel.h"

static NSString *recomendKey = @"recomendKey";

@interface LTContactManager()

@property(nonatomic,copy) NSString *hostIp;
@end


@implementation LTContactManager

-(NSMutableArray *)contactMangerdelegateArray
{
    if(_contactMangerdelegateArray == nil)
    {
        _contactMangerdelegateArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _contactMangerdelegateArray;
}
-(void)addDelegate:(id<LTContactManagerDelegate>)deleagte
{
    [self.contactMangerdelegateArray addObject:deleagte];

}
-(void)removeDelegate:(id<LTContactManagerDelegate>)delegate
{
    [self.contactMangerdelegateArray removeObject:delegate];
    
}
-(NSArray *)getAllApplyMessage
{
    return [[LTDBHelper sharedbhelper] getAllApplyWithUserID:[LTClient sharedClient].currentUserId];
    
}
-(NSInteger)getApplyMessageWithUnRead
{
    return [[LTDBHelper sharedbhelper] getAllUnreadApplyMessage];
}
-(BOOL)markAllApplyMessagesAsRead
{
    return [[LTDBHelper sharedbhelper] markAllApplyMessagesAsRead];
}
-(void)updateContacts:(NSArray *)contacts
{
    [[LTDBHelper sharedbhelper] updateUser:contacts];

}
-(void)updateContact:(LTUser  *)user
{
    BOOL res =    [[LTDBHelper sharedbhelper] AddUser:user];
    if(res)
    {
        for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
            if(contactmanger && [contactmanger respondsToSelector:@selector(friendListChange)]){
                [contactmanger friendListChange];
            }
        }
    }
}

-(NSArray *)getContactsFromDB;
{
    return  [[LTDBHelper sharedbhelper] getFriendUser];
}
-(LTUser *)getUserWithUserId:(NSString *)userId
{
   return  [[LTDBHelper sharedbhelper] getUserWithUserId:userId];
}

-(BOOL)isFriendWithUserId:(NSString *)userId
{
    return [[LTDBHelper sharedbhelper] isFriendWithUserId:userId];
}
/**
 判断是否是自己
 
 @param userId userId
 @return bool
 */
-(BOOL)isMyselfWithUserId:(NSString *)userId
{
    if([userId isEqualToString:[LTClient sharedClient].currentUserId])
    {
        return YES;
    }else
    {
        return NO;
    }
}

-(BOOL)isFriendWithAccount:(NSString *)account
{

    return YES;
}
-(BOOL)DeleteFriendWithUserId:(NSString *)userId
{

    BOOL res =    [[LTDBHelper sharedbhelper] deleteUser:userId];
    [[LTDBHelper sharedbhelper] deleteAppleMessageFromSinceUserId:userId];
    if(res)
    {
        for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
            if(contactmanger && [contactmanger respondsToSelector:@selector(friendListChange)]){
                [contactmanger friendListChange];
            }
        }
    }
    return res;
}
-(BOOL)AddFriendWithUserToDB:(LTUser *)user
{
    BOOL res =   [[LTDBHelper sharedbhelper] AddUser:user];
    if(res)
    {
        for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
            if(contactmanger && [contactmanger respondsToSelector:@selector(friendListChange)]){
                [contactmanger friendListChange];
            }
        }
    }
    return res;
}
-(void)getContactsFromServer:(void (^)(NSArray<LTUser *> *, LTError *))completionBlock
{
    
    [[LTHTTPTool shareTool] getPath:@"/user/friends/get_all_friends" parameters:nil success:^(LTBaseDataModel *datamodel) {
        
        NSMutableArray *userArray = [LTUser  mj_objectArrayWithKeyValuesArray:datamodel.data];
        
        [[LTDBHelper sharedbhelper] updateUser:userArray];
        
        completionBlock(userArray,nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        
        LTError *lterror = [LTError errorWithDescription:datamodel.message code:-1];
        completionBlock(nil,lterror);
        
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        completionBlock(nil,lterror);
    }];
}

- (void)deleteContact:(LTUser  *)user
 isDeleteConversation:(BOOL)IsDeleteConversation
           completion:(void(^)(LTUser *user, LTError *lterror))CompletionBlock
{
    
    NSDictionary *param = @{@"friendId":user.userId};
    [[LTHTTPTool shareTool] postPath:@"/user/friends/delete" parameters:param success:^(LTBaseDataModel *datamodel) {
        BOOL res =    [[LTDBHelper sharedbhelper] deleteUser:user.userId];
        if(IsDeleteConversation){
          [[LTDBHelper sharedbhelper] DeleteConversationWithConversationID:user.userId];
        }
        [[LTDBHelper sharedbhelper] deleteAppleMessageFromSinceUserId:user.userId];
        if(res)
        {
            for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(friendListChange)]){
                    [contactmanger friendListChange];
                }
            }
        }
        [[LTSendMessageHelper helper] sendDeletFriendMessage:user completion:^(LTUser *ltuser, LTError *ltrror) {
            CompletionBlock(ltuser,ltrror);
        }];
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:datamodel.message code:-1];
        CompletionBlock(nil,lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        CompletionBlock(nil,lterror);
    }];

}

-(void)addContact:(LTUser *)ltuer
           message:(NSString *)message
        completion:(void(^)(LTUser *ltuser, LTError *ltrror))CompletionBlock
{

    NSDictionary *param = @{@"friendId":ltuer.userId,
                            @"addReason":message};
    
    [[LTHTTPTool shareTool] postPath:@"/user/friends/apply" parameters:param success:^(LTBaseDataModel *datamodel) {
        
      [[LTSendMessageHelper helper] sendAddFriendMessage:ltuer message:message completion:CompletionBlock];
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:@"参数错误" code:-1];
        CompletionBlock(ltuer,lterror);
    } failer:^(NSError *error) {
        
        LTError *lterror = [LTError errorWithDescription:@"网路错误" code:-1];
        CompletionBlock(ltuer,lterror);
    }];
}

 //同意加好友的申请
- (void)approveFriendRequestFromUser:(LTUser *)ltuser
                           applyBody:(LTMessageApplyBody *)body
                          completion:(void(^)(LTUser *ltuser,LTError *ltrror))CompletionBlock
{

    NSDictionary *param = @{@"friendId":ltuser.userId};
    [[LTHTTPTool shareTool] getPath:@"/user/friends/apply_agree" parameters:param success:^(LTBaseDataModel *datamodel) {
        [[LTSendMessageHelper helper] sendAgreeFriendMessage:ltuser applyBody:body completion:^(LTUser *ltuser, LTError *ltrror) {
            if(ltrror == nil)
            {
                for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
                    if(contactmanger && [contactmanger respondsToSelector:@selector(friendListChange)]){
                        [contactmanger friendListChange];
                    }
                }
            }
            CompletionBlock(ltuser,ltrror);
        }];
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:@"参数错误" code:-1];
        CompletionBlock(ltuser,lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网路错误" code:-1];
        CompletionBlock(ltuser,lterror);
    }];
}

- (void)declineFriendRequestFromUser:(LTUser *)ltuser
                           applyBody:(LTMessageApplyBody *)body
                          completion:(void(^)(LTUser *ltuser,LTError *ltrror))CompletionBlock
{
     NSString *path = [NSString stringWithFormat:@"/v1/user/%@/refuse/%@",[LTClient sharedClient].currentUserId,ltuser.userId];
    
    [[LTHTTPTool shareTool] postPath:path parameters:nil success:^(LTBaseDataModel *datamodel) {
        
        [[LTSendMessageHelper helper] sendrefuseFriendMessage:ltuser applyBody:body completion:CompletionBlock];

    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:@"参数错误" code:-1];
        CompletionBlock(ltuser,lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网路错误" code:-1];
        CompletionBlock(ltuser,lterror);
    }];
}

-(BOOL)deleteAppleMessage:(NSString *)applyMessageId
{
    return  [[LTDBHelper sharedbhelper] deleteAppleMessage:applyMessageId];

}


/**
 更新用户信息
 
 @param name 更新用户信息
 @param CompletionBlock 更新用户信息完成的block
 */
-(void)updateCurrentUserInfoName:(NSString  *)name
                      completion:(void(^)(LTError *ltrror))CompletionBlock
{
    NSDictionary *param = @{@"name":name};
    
    [self updateCurrentUserInfo:param completion:^(LTError *ltrror) {
        if(ltrror == nil)
        {
            [LTClient sharedClient].currentUser.name = name;
            for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(curentUserInfoChange)]){
                    [contactmanger curentUserInfoChange];
                }
            }
            
        }
        CompletionBlock(ltrror);
    }];
    
    
}

-(void)updateCurrentUserInfoAvatar:(NSString  *)avatar
                      completion:(void(^)(LTError *ltrror))CompletionBlock
{
    NSDictionary *param = @{@"avatar":avatar};
    [self updateCurrentUserInfo:param completion:^(LTError *ltrror) {
        if(ltrror == nil)
        {
            [LTClient sharedClient].currentUser.avatar = avatar;
            for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(curentUserInfoChange)]){
                    [contactmanger curentUserInfoChange];
                }
            }
        }
         CompletionBlock(ltrror);
        
    }];
    
    
}

-(void)updateCurrentUserInfoCover:(NSString  *)cover
                      completion:(void(^)(LTError *ltrror))CompletionBlock
{
    NSDictionary *param = @{@"cover":cover};
    [self updateCurrentUserInfo:param completion:^(LTError *ltrror) {
        if(ltrror == nil)
        {
            [LTClient sharedClient].currentUser.cover = cover;
            for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(curentUserInfoChange)]){
                    [contactmanger curentUserInfoChange];
                }
            }
            
        }
         CompletionBlock(ltrror);
    }];
    
    
}

-(void)updateCurrentUserInfoSignature:(NSString  *)signature
                      completion:(void(^)(LTError *ltrror))CompletionBlock
{
    NSDictionary *param = @{@"signature":signature};
    [self updateCurrentUserInfo:param completion:^(LTError *ltrror) {
        if(ltrror == nil)
        {
            [LTClient sharedClient].currentUser.signature = signature;
            for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(curentUserInfoChange)]){
                    [contactmanger curentUserInfoChange];
                }
            }
            
        }
         CompletionBlock(ltrror);
    }];
    
    
}

-(void)updateCurrentUserInfoGender:(int)gender
                           completion:(void(^)(LTError *ltrror))CompletionBlock
{
    NSDictionary *param = @{@"gender":@(gender)};
    [self updateCurrentUserInfo:param completion:^(LTError *ltrror) {
        if(ltrror == nil)
        {
            [LTClient sharedClient].currentUser.gender = gender;
            for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(curentUserInfoChange)]){
                    [contactmanger curentUserInfoChange];
                }
            }
            
        }
        CompletionBlock(ltrror);
    }];
    
    
}

-(void)updateCurrentUserInfo:(NSDictionary *)param
                  completion:(void(^)(LTError *ltrror))CompletionBlock
{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:param];
    [dict setObject:[LTClient sharedClient].currentUserId forKey:@"id"];
    
    [[LTHTTPTool shareTool] postPath:@"/user/update" parameters:dict success:^(LTBaseDataModel *datamodel) {
        
        CompletionBlock(nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        
        LTError *lterror = [LTError errorWithDescription:@"网路错误" code:-1];
        CompletionBlock(lterror);
        
    } failer:^(NSError *error) {
        
        LTError *lterror = [LTError errorWithDescription:@"网路错误" code:-1];
         CompletionBlock(lterror);

    }];


}


/**
 获取好友配置信息(先从本地数据去去查找，没找到在去服务器去取)
 
 @param friendId    好友的userId
 @param CompletionBlock 获取完成的blcok
 */
-(void)getUserConfigWithFriendId:(NSString *)friendId
                      completion:(void(^)(LTUserConfig *userConfig,LTError *ltrror))CompletionBlock
{
    LTUserConfig *config = nil; // [[LTDBHelper sharedbhelper] getUserConfigWithfriendId:friendId];
    
    if(config != nil)
    {
        CompletionBlock(config,nil);
    }else
    {
        NSDictionary *param = @{@"friendId":friendId};
        [[LTHTTPTool shareTool] postPath:@"/user_config/get_friend_config" parameters:param success:^(LTBaseDataModel *datamodel) {
            LTUserConfig *config = [LTUserConfig mj_objectWithKeyValues:datamodel.data];
            [[LTDBHelper sharedbhelper] AddORUpdateUserConfig:config];
            
            CompletionBlock(config,nil);
            
            
        } parmerror:^(LTBaseDataModel *datamodel) {
            LTError *lterror = [LTError errorWithDescription:@"参数错误" code:-1];
            CompletionBlock(nil,lterror);
        } failer:^(NSError *error) {
            
            LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
            CompletionBlock(nil,lterror);
        }];
    }
}

/**
 更新好友配置信息
 
 @param userconfig     配置model
 @param CompletionBlock  更改完成的回调
 */
-(void)updateUserConfigWithConfig:(LTUserConfig *)userconfig
                       completion:(void(^)(LTError *ltrror))CompletionBlock
{
    NSDictionary *param = @{@"id":userconfig.id,
                            @"userId":[LTClient sharedClient].currentUserId,
                            @"friendId":userconfig.friendId,
                            @"top":@(userconfig.top),
                            @"notify":@(userconfig.notify),
                            @"allowFriendSeeMyMoment":@(userconfig.allowFriendSeeMyMoment),
                            @"shieldFriendMoment":@(userconfig.shieldFriendMoment),
                            @"black":@(userconfig.black),
                            @"remark":userconfig.remark,
                            @"push":@(userconfig.push),
                            @"chatBackground":userconfig.chatBackground};
    [[LTHTTPTool shareTool] postPath:@"/user_config/update_friend_config" parameters:param success:^(LTBaseDataModel *datamodel) {
        [[LTDBHelper sharedbhelper] AddORUpdateUserConfig:userconfig];
        CompletionBlock(nil);
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:@"参数错误" code:-1];
        CompletionBlock(lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        CompletionBlock(lterror);
    }];
    
}
-(void)updateRecomendMessage:(NSString *)recomend
{
    
    [[NSUserDefaults standardUserDefaults] setObject:recomend forKey:recomendKey];
    for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
        if(contactmanger && [contactmanger respondsToSelector:@selector(friendRecomendChange)]){
            [contactmanger friendRecomendChange];
        }
    }
}

-(LTFriendRecmondModel *)getRecomendMessage
{
    NSString *recomend = [[NSUserDefaults standardUserDefaults] objectForKey:recomendKey];
    if(recomend != nil)
    {
        LTFriendRecmondModel *recomendModel = [LTFriendRecmondModel mj_objectWithKeyValues:recomend];
        return recomendModel;
    }else
    {
        return nil;
    }
  
}

-(void)clearRecomendMessage
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:recomendKey];
    
    for (id<LTContactManagerDelegate> contactmanger in self.contactMangerdelegateArray) {
        if(contactmanger && [contactmanger respondsToSelector:@selector(clearRecomend)]){
            [contactmanger clearRecomend];
        }
    }

}
@end
